package com.sgb.kjwl.view.ui.activity.self.logistics;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AppActivityQuotedOwnerBinding;
import com.sgb.kjwl.model.entity.self.OrderQuoteEntity;
import com.sgb.kjwl.model.entity.transport.FreightProEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.OfferStatisticsEntity;
import com.sgb.kjwl.model.entity.transport.OwnerGoodsDetailInfo;
import com.sgb.kjwl.model.entity.transport.QuotedListOwnerViewEntity;
import com.sgb.kjwl.utils.DisplayUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.util.PermissionCheckUtil;
import com.swgk.core.util.UserOperating;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.AuthActivity3;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.self.logistics.OfferOwnerAdapter3;
import com.sgb.kjwl.view.widget.FilterTypePopWindow;
import com.sgb.kjwl.view.widget.MapQuotePopWindow;
import com.sgb.kjwl.view.widget.PresentTimePopWindow;
import com.sgb.kjwl.view.widget.transport.OfferStatisticsDialog;
import com.sgb.kjwl.view.widget.transport.SourceListPopWindow;
import com.sgb.kjwl.view.widget.transport.IconExplainDialog;
import com.sgb.kjwl.view.widget.transport.QuickMenuPopWindow;
import com.sgb.kjwl.viewmodel.self.logistics.QuotedOwnerModel;
import com.swgk.core.customview.WSTextView;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.ResolutionUtil;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * Describe:    报价单位 —— 竞价货源  （货主视角）
 * Author:  yangLei
 * Date:    2021/8/27
 */
@Route(path = AppRouteConstant.WuLui.ROUTER_PATH_QUOED_OWNER_ACTIVITY)
public class QuotedOwnerActivity extends AppActivity implements QuickMenuPopWindow.MenuClickResult, SourceListPopWindow.ItemClickResult {

    public QuotedOwnerModel viewModel;
    private AppActivityQuotedOwnerBinding mBinding;

    //列表数据适配器
    private OfferOwnerAdapter3 quotedAdapter;
    private OfferOwnerAdapter3 receiveAdapter;
    private AMap aMap;    //地图控制器
    private MapView mapView;    //高德3DMap  地图显示View

    private String goodsNo;

    private BottomSheetBehavior sheetBehavior;
    private int peekHeight = 165;
    //路径信息加载显示完成
    private boolean routeAddressCompleted = false;
    //货物类型信息加载显示完成
    private boolean goodsDetailsCompleted = false;

    private QuickMenuPopWindow menuPop;//快捷菜单弹窗
    private IconExplainDialog iconExplainDialog;//图标说明弹窗
    private SourceListPopWindow sourceListPop;//竞价货源项目列表弹窗
    private MapQuotePopWindow quotePop;//报价单位信息弹窗
    private PresentTimePopWindow arriveTimePop;//到场时间弹窗
    private FilterTypePopWindow distancePop;//距离装货地
    private FilterTypePopWindow carTypePop;//车型
    private FilterTypePopWindow morePop;//更多筛选（接单或者报价的类型）
    private OfferStatisticsDialog statisticsDialog;//报价统计弹窗

    private int currTab = 0;//当前位置：0-报价 1-接单    2-发货
    private OwnerGoodsDetailInfo detailInfo;
    private QuotedListOwnerViewEntity currQuotedListEntity;

    public static void start(Context context, String sourceNo) {
        Intent intent = new Intent(context, QuotedOwnerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("no", sourceNo);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mapView != null)
            mapView.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        goodsNo = getIntent().getStringExtra("no");
        if (TextUtils.isEmpty(goodsNo)) {
            finish();
        }
        mBinding = DataBindingUtil.setContentView(QuotedOwnerActivity.this, R.layout.app_activity_quoted_owner);
        sheetBehavior = BottomSheetBehavior.from(mBinding.layoutBehavior);
        settingTitleIv(false);
        mBinding.include.rightImageView.setImageResource(R.mipmap.icon_three_point_white);
        viewModel = new ViewModelProvider(this).get(QuotedOwnerModel.class);
        mapView = mBinding.mapView;

        initMap();
        initEvent();
        initPop();
        initList();
        RequestSourceInfo();
    }

    private void initList() {
        //地图页列表初始化
        if (quotedAdapter == null)
            quotedAdapter = new OfferOwnerAdapter3(this, null);
        quotedAdapter.setOnItemClick(new AdapterOnItemClick<OrderQuoteEntity>() {
            @Override
            public void onItemClick(OrderQuoteEntity orderQuoteEntity, int position) {
                if (orderQuoteEntity != null) {
                    showQuotedDetailsPop(orderQuoteEntity);
                }
            }
        });

        if (receiveAdapter == null)
            receiveAdapter = new OfferOwnerAdapter3(this, null);
        receiveAdapter.setOnItemClick(new AdapterOnItemClick<OrderQuoteEntity>() {
            @Override
            public void onItemClick(OrderQuoteEntity orderQuoteEntity, int position) {
                if (orderQuoteEntity != null) {
                    showQuotedDetailsPop(orderQuoteEntity);
                }
            }
        });

        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.shape_list_divider_10dp));
        mBinding.list.addItemDecoration(divider);
        LinearLayoutManager layoutManager2 = new LinearLayoutManager(this);
        mBinding.list.setLayoutManager(layoutManager2);
        mBinding.list.setAdapter(quotedAdapter);
        mBinding.list.setLoadingMoreEnabled(false);
        mBinding.list.setPullRefreshEnabled(false);
        mBinding.smartRefresh.setEnableRefresh(false);

        mBinding.smartRefresh.setOnLoadMoreListener(refreshLayout -> {
            loadingMoreData();
        });

        quotedAdapter.setOnTabClickListener(new OfferOwnerAdapter3.OnTabClickListener() {
            @Override
            public void onAgreeClick(OrderQuoteEntity entity) {
                viewModel.agreeOffer(QuotedOwnerActivity.this, entity.getGoodsOfferNo(), entity.getSourceNo());
            }

            @Override
            public void onChat(String account) {
                // TODO IM功能目前需要全部去掉，此处需要后期IM迁移完成后完善
                buildSingleTalking(account);
            }
        });

        receiveAdapter.setOnTabClickListener(new OfferOwnerAdapter3.OnTabClickListener() {
            @Override
            public void onAgreeClick(OrderQuoteEntity entity) {
                viewModel.agreeOffer(QuotedOwnerActivity.this, entity.getGoodsOfferNo(), entity.getSourceNo());
            }

            @Override
            public void onChat(String account) {
                // TODO IM功能目前需要全部去掉，此处需要后期IM迁移完成后完善
                buildSingleTalking(account);
            }
        });
    }

    private void initPop() {
        if (menuPop == null) {
            menuPop = new QuickMenuPopWindow(this, 1);
        }
        menuPop.setClickResult(this::onResult);

        if (sourceListPop == null) {
            sourceListPop = new SourceListPopWindow(this);
        }
        sourceListPop.setItemClickResult(this::onResult);
        sourceListPop.setOnDismissListener(() -> {
            settingTitleIv(false);
            mBinding.bgProPop.setVisibility(View.GONE);
        });

        //报价方报价详情弹窗
        if (quotePop == null) {
            quotePop = MapQuotePopWindow.newInstance(this, 0, entity -> {
                agreeOfferRefresh(false);
            });
        }
        quotePop.setOnDismissListener(() -> {
            mBinding.bgQuotedInfoPop.setVisibility(View.GONE);
            viewModel.resetMarkersSmall();
        });

        //到场时间选择弹窗
        arriveTimePop = new PresentTimePopWindow(this);
        arriveTimePop.setOnResultClick((key1, key2, key3) -> {
            long startTime = (long) key1;
            long endTime = (long) key2;
            if (startTime <= 0) {
                viewModel.searchEntity.setStartInTime("");
            } else
                viewModel.searchEntity.setStartInTime(startTime + "");
            if (endTime <= 0) {
                viewModel.searchEntity.setEndInTime("");
            } else
                viewModel.searchEntity.setEndInTime(endTime + "");
            //当选择了装货时间后根据条件重新搜索
            viewModel.searchEntity.setSearchType(-1);
            //刷新数据
            viewModel.getTickSizeListInfo(this, false);
        });
        arriveTimePop.setOnDismissListener(() -> {
            if (!TextUtils.isEmpty(viewModel.searchEntity.getStartInTime()) || !TextUtils.isEmpty(viewModel.searchEntity.getEndInTime())) {
                setFilterTabStatues(mBinding.arriveTimeLl, mBinding.arriveTimeTv, mBinding.arriveTimeIv, 1);
            } else {
                setFilterTabStatues(mBinding.arriveTimeLl, mBinding.arriveTimeTv, mBinding.arriveTimeIv, 0);
            }
        });

        //距装货地选择弹窗
        distancePop = new FilterTypePopWindow(this);
        distancePop.setOnResultClick((key1, key2, key3) -> {
            GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) key1;
            if (entity != null && !TextUtils.isEmpty(entity.getNo()) && !TextUtils.isEmpty(entity.getName())) {
                if (entity.getNo().equals("0")) {
                    viewModel.searchEntity.setDistancePlace(null);
                    mBinding.distanceTv.setText("距装货地");
                } else {
                    mBinding.distanceTv.setText(tabTitleEchoHandle(entity.getName(), 4));
                    viewModel.searchEntity.setDistancePlace(Integer.valueOf(entity.getNo()));
                }
                viewModel.searchEntity.setSearchType(-1);
                //刷新数据
                viewModel.getTickSizeListInfo(this, false);
            }
        });
        distancePop.setOnDismissListener(() -> {
            if (viewModel.searchEntity.getDistancePlace() != null) {
                setFilterTabStatues(mBinding.distanceIvLl, mBinding.distanceTv, mBinding.distanceIv, 1);
            } else {
                setFilterTabStatues(mBinding.distanceIvLl, mBinding.distanceTv, mBinding.distanceIv, 0);
            }
        });

        //车型选择弹窗
        carTypePop = new FilterTypePopWindow(this);
        carTypePop.setOnResultClick((key1, key2, key3) -> {
            GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) key1;
            if (entity != null && !TextUtils.isEmpty(entity.getNo()) && !TextUtils.isEmpty(entity.getName())) {
                if (entity.getNo().equals("0")) {
                    viewModel.searchEntity.setCarTypeNo(null);
                    mBinding.carTypeTv.setText("车型");
                } else {
                    viewModel.searchEntity.setCarTypeNo(entity.getNo());
                    mBinding.carTypeTv.setText(tabTitleEchoHandle(entity.getName(), 4));
                }
                viewModel.searchEntity.setSearchType(-1);
                //刷新数据
                viewModel.getTickSizeListInfo(this, false);
            }
        });
        carTypePop.setOnDismissListener(() -> {
            if (viewModel.searchEntity.getCarTypeNo() != null) {
                setFilterTabStatues(mBinding.carTypeLl, mBinding.carTypeTv, mBinding.carTypeIv, 1);
            } else {
                setFilterTabStatues(mBinding.carTypeLl, mBinding.carTypeTv, mBinding.carTypeIv, 0);
            }
        });

        //接单或者报价类型选择弹窗
        morePop = new FilterTypePopWindow(this, "报价/接单车主");
        morePop.setOnResultClick((key1, key2, key3) -> {
            GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) key1;
            if (entity != null && !TextUtils.isEmpty(entity.getNo()) && !TextUtils.isEmpty(entity.getName())) {
                switch (entity.getNo()) {
                    case "0":
                        viewModel.searchEntity.setOfferType("");
                        break;
                    case "1":
                        viewModel.searchEntity.setOfferType("1");
                        break;
                    case "2":
                        viewModel.searchEntity.setOfferType("2");
                        break;
                    case "3":
                        viewModel.searchEntity.setOfferType("3");
                        break;
                }
                viewModel.searchEntity.setSearchType(-1);
                //刷新数据
                viewModel.getTickSizeListInfo(this, false);
            }
        });
        morePop.setOnDismissListener(() -> {
            mBinding.bgFilterPop.setVisibility(View.GONE);
        });

        initPopData();
    }

    /**
     * 筛选框选择结果回显处理
     *
     * @param title 源字符串
     * @param size  显示长度
     * @return
     */
    private String tabTitleEchoHandle(String title, int size) {
        if (TextUtils.isEmpty(title))
            return "";

        if (size <= 0)
            size = 1;
        if (title.length() <= size) {
            return title;
        } else {
            return title.substring(0, size) + "...";
        }
    }

    /**
     * 初始化筛选框数据
     */
    private void initPopData() {
        //距离装货地信息
        List<GoodsInfoTypeEntity3> distanceInfo = new ArrayList<>();
        distanceInfo.add(new GoodsInfoTypeEntity3("0", "不限"));
        distanceInfo.add(new GoodsInfoTypeEntity3("10", "10km以内"));
        distanceInfo.add(new GoodsInfoTypeEntity3("30", "30km以内"));
        distanceInfo.add(new GoodsInfoTypeEntity3("50", "50km以内"));
        distanceInfo.add(new GoodsInfoTypeEntity3("70", "70km以内"));
        distanceInfo.add(new GoodsInfoTypeEntity3("90", "90km以内"));
        distancePop.setData(distanceInfo, 0);

        //接单或报价类型信息
        List<GoodsInfoTypeEntity3> quotedTypeInfo = new ArrayList<>();
        quotedTypeInfo.add(new GoodsInfoTypeEntity3("0", "不限"));
        quotedTypeInfo.add(new GoodsInfoTypeEntity3("1", "企业"));
        quotedTypeInfo.add(new GoodsInfoTypeEntity3("2", "团队"));
        quotedTypeInfo.add(new GoodsInfoTypeEntity3("3", "个人"));
        morePop.setData(quotedTypeInfo, 0);

        viewModel.getCarTypeList();
    }

    private void settingTitleIv(boolean isExpand) {
        Drawable drawable;
        if (isExpand) {
            drawable = getResources().getDrawable(R.mipmap.icon_list_to_pack_up);
        } else {
            drawable = getResources().getDrawable(R.mipmap.icon_list_to_unfold);
        }
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        mBinding.include.titleView.setCompoundDrawables(null, null, drawable, null);
    }

    private void initEvent() {
        mBinding.setOnClick(this);
        mBinding.include.titleView.setOnClickListener(this::onClick);
        mBinding.include.rightImageView.setOnClickListener(this::onClick);
        mBinding.include.ivBack.setOnClickListener(this::onClick);
        mBinding.bgProPop.setOnClickListener(this::onClick);

        //底部弹窗视图Behavior
        sheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                switch (newState) {
                    case BottomSheetBehavior.STATE_COLLAPSED:
                        //折叠状态
                        mBinding.arrowsIv.setImageResource(R.mipmap.icon_ex_lay_up);
                        mBinding.scrollView.smoothScrollTo(0, 0);
                        break;

                    case BottomSheetBehavior.STATE_DRAGGING:
                        //拖拽状态
                    case BottomSheetBehavior.STATE_EXPANDED:
                        //完全展开
                        mBinding.arrowsIv.setImageResource(R.mipmap.icon_ex_lay_down);
                        break;
                    case BottomSheetBehavior.STATE_HIDDEN:
                        //隐藏状态
                    case BottomSheetBehavior.STATE_SETTLING:
                        //脱离手指自由滑动状态
                        mBinding.arrowsIv.setImageResource(R.mipmap.icon_ex_lay_up);
                        break;
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {

            }
        });

        viewModel.detailsLiveData.observe(this, ownerGoodsDetailInfo -> setDetail(ownerGoodsDetailInfo));
        viewModel.proListLD.observe(this, biddingProEntities -> {
            if (biddingProEntities != null && biddingProEntities.size() > 0) {
                biddingProEntities.get(0).setSelect(true);
            }
            sourceListPop.setData(biddingProEntities);
        });

        viewModel.quotedListLD.observe(this, quotedListEntity -> refreshQuotedListInfo(quotedListEntity));

        viewModel.ldCurrOffer.observe(this, integer -> {
            if (integer != null) {
                if (integer >= 0 && viewModel.getValidBeans().size() > integer) {
                    OrderQuoteEntity quoteEntity = viewModel.getValidBeans().get(integer);
                    showQuotedDetailsPop(quoteEntity);
                }
            }
        });

        viewModel.ldCarType.observe(this, goodsInfoTypeEntity3s -> {
            if (carTypePop != null && goodsInfoTypeEntity3s != null) {
                goodsInfoTypeEntity3s.add(0, new GoodsInfoTypeEntity3("0", "不限"));
                carTypePop.setData(goodsInfoTypeEntity3s, 0);
            }
        });

        viewModel.ldAgree.observe(this, a -> agreeOfferRefresh(true));
    }

    private void showQuotedDetailsPop(OrderQuoteEntity quoteEntity) {
        if (quotePop != null) {
            if (sheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
                sheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            }
            quotePop.setData(quoteEntity);
            quotePop.showDownPopwindow(mBinding.iconExplainPop, false);
            mBinding.bgQuotedInfoPop.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 加载报价列表信息
     *
     * @param entity
     */
    private void refreshQuotedListInfo(QuotedListOwnerViewEntity entity) {
        mBinding.smartRefresh.finishLoadMore();
        currQuotedListEntity = entity;
        //刷新报价统计弹窗信息
        refreshStatistics();

        //数据请求结束，在地图上添加marker
        viewModel.addAllMarkers(this, 1);
        if (entity == null) {
            return;
        }
        String type = entity.getSearchType();
        if (type.equals("-1")) {
            if (entity.getOrderQuoteCount() != null) {
                mBinding.offerTabTv.setText(String.format("车主报价(%d)", entity.getOrderQuoteCount()));
            } else {
                mBinding.offerTabTv.setText("车主报价(0)");
            }
            if (entity.getOrderReceivingCount() != null) {
                mBinding.receiveTabTv.setText(String.format("车主接单(%d)", entity.getOrderReceivingCount()));
            } else {
                mBinding.receiveTabTv.setText("车主接单(0)");
            }

            if (entity.getOrderQuoteList() != null && entity.getOrderQuoteList().size() > 0) {
                quotedAdapter.setDatas(entity.getOrderQuoteList());
                if (currTab == 0) {
                    mBinding.emptyOfferLay.setVisibility(View.GONE);
                    mBinding.list.setVisibility(View.VISIBLE);
                }
            } else {
                quotedAdapter.setDatas(new ArrayList<>());
                if (currTab == 0) {
                    mBinding.emptyOfferLay.setVisibility(View.VISIBLE);
                    mBinding.list.setVisibility(View.GONE);
                }
            }

            if (entity.getOrderReceivingList() != null && entity.getOrderReceivingList().size() > 0) {
                receiveAdapter.setDatas(entity.getOrderReceivingList());
                if (currTab == 1) {
                    mBinding.emptyOfferLay.setVisibility(View.GONE);
                    mBinding.list.setVisibility(View.VISIBLE);
                }
            } else {
                receiveAdapter.setDatas(new ArrayList<>());
                if (currTab == 1) {
                    mBinding.emptyOfferLay.setVisibility(View.VISIBLE);
                    mBinding.list.setVisibility(View.GONE);
                }
            }

        } else if (type.equals("0")) {//报价
            if (entity.getPagesVO() != null) {
                mBinding.offerTabTv.setText(String.format("车主报价(%d)", entity.getPagesVO().getTotalRow()));
                if (entity.isRefresh()) {
                    quotedAdapter.setDatas(entity.getPagesVO().getList());
                    if (currTab == 0) {
                        mBinding.emptyOfferLay.setVisibility(View.GONE);
                        mBinding.list.setVisibility(View.VISIBLE);
                    }
                } else {
                    quotedAdapter.addDatas(entity.getPagesVO().getList());
                    if (currTab == 0) {
                        mBinding.emptyOfferLay.setVisibility(View.VISIBLE);
                        mBinding.list.setVisibility(View.GONE);
                    }
                }
            }
        } else if (type.equals("2")) {//接单
            if (entity.getPagesVO() != null) {
                mBinding.receiveTabTv.setText(String.format("车主接单(%d)", entity.getPagesVO().getTotalRow()));
                if (entity.isRefresh()) {
                    receiveAdapter.setDatas(entity.getPagesVO().getList());
                    if (currTab == 1) {
                        mBinding.emptyOfferLay.setVisibility(View.GONE);
                        mBinding.list.setVisibility(View.VISIBLE);
                    }
                } else {
                    receiveAdapter.addDatas(entity.getPagesVO().getList());
                    if (currTab == 1) {
                        mBinding.emptyOfferLay.setVisibility(View.VISIBLE);
                        mBinding.list.setVisibility(View.GONE);
                    }
                }
            }
        }
    }

    /**
     * 刷新统计信息
     */
    private void refreshStatistics() {
        if (currQuotedListEntity == null)
            return;
        if (statisticsDialog == null)
            statisticsDialog = OfferStatisticsDialog.newInstance(this, 1);
        String priceStr = "";
        if (detailInfo != null) {
            if (!TextUtils.isEmpty(detailInfo.getFreight()) && !TextUtils.isEmpty(detailInfo.getFreightUnit())) {
                priceStr = NumberUtil.trim0(detailInfo.getFreight()) + detailInfo.getFreightUnit();
            }
        }
        OfferStatisticsEntity statisticsEntity;
        if (currQuotedListEntity != null && currQuotedListEntity.getVo() != null) {
            statisticsEntity = new OfferStatisticsEntity(currQuotedListEntity.getVo().getP1(), currQuotedListEntity.getVo().getP2(), currQuotedListEntity.getVo().getP3(),
                    currQuotedListEntity.getVo().getP4(), currQuotedListEntity.getVo().getP5(), currQuotedListEntity.getVo().getP6(), priceStr);
        } else {
            statisticsEntity = new OfferStatisticsEntity(0, 0, 0,
                    0, 0, 0, priceStr);
        }
        statisticsDialog.setStatisticsEntity(statisticsEntity);
    }

    /**
     * 请求货源信息
     */
    private void RequestSourceInfo() {
        viewModel.getOwnerGoodsDetailInfo(this, goodsNo);
        viewModel.getBiddingProList(goodsNo);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;

            case R.id.icon_explain_pop:
                if (statisticsDialog == null)
                    statisticsDialog = OfferStatisticsDialog.newInstance(this, 1);
                if (detailInfo == null)//货源信息未请求下来不展示
                    return;
                statisticsDialog.show();
                break;

            case R.id.right_image_view:
                if (menuPop != null) {
                    menuPop.showAsDropDown(mBinding.include.rightImageView, 0, -40);
                }
                break;

            case R.id.title_view:
                if (sourceListPop.isShowing()) {
                    sourceListPop.dismiss();
                    mBinding.bgProPop.setVisibility(View.GONE);
                } else {
                    sourceListPop.showAsDropDown(mBinding.include.topLayout, 0, 0);
                    settingTitleIv(true);
                    mBinding.bgProPop.setVisibility(View.VISIBLE);
                }
                break;

            case R.id.source_info_bar:
                break;

            case R.id.arrows_iv_bar:
                if (sheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
                    sheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                } else {
                    sheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                }
                break;

            case R.id.offer_tab_ll://点击车主报价
                currTab = 0;
                mBinding.offerTabTv.setTextColor(Color.parseColor("#EF4033"));
                mBinding.offerTabTv.setBold(WSTextView.BOLD_MEDIUM);
                mBinding.offerTabStrip.setVisibility(View.VISIBLE);
                mBinding.receiveTabTv.setTextColor(Color.parseColor("#333333"));
                mBinding.receiveTabTv.setBold(WSTextView.BOLD_REGULAR);
                mBinding.receiveTabStrip.setVisibility(View.INVISIBLE);
                mBinding.shippedTabTv.setTextColor(Color.parseColor("#333333"));
                mBinding.shippedTabTv.setBold(WSTextView.BOLD_REGULAR);
                mBinding.shippedTabStrip.setVisibility(View.INVISIBLE);

                //切换需要展示的数据源
                mBinding.list.setAdapter(quotedAdapter);
                if (quotedAdapter.getDatas().size() > 0) {
                    mBinding.list.setVisibility(View.VISIBLE);
                    mBinding.emptyOfferLay.setVisibility(View.GONE);
                } else {
                    mBinding.list.setVisibility(View.GONE);
                    mBinding.emptyOfferLay.setVisibility(View.VISIBLE);
                }

                if (sheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
                    sheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                }

                break;

            case R.id.receive_tab_ll://点击车主接单
                currTab = 1;
                mBinding.offerTabTv.setTextColor(Color.parseColor("#333333"));
                mBinding.offerTabTv.setBold(WSTextView.BOLD_REGULAR);
                mBinding.offerTabStrip.setVisibility(View.INVISIBLE);
                mBinding.receiveTabTv.setTextColor(Color.parseColor("#EF4033"));
                mBinding.receiveTabTv.setBold(WSTextView.BOLD_MEDIUM);
                mBinding.receiveTabStrip.setVisibility(View.VISIBLE);
                mBinding.shippedTabTv.setTextColor(Color.parseColor("#333333"));
                mBinding.shippedTabTv.setBold(WSTextView.BOLD_REGULAR);
                mBinding.shippedTabStrip.setVisibility(View.INVISIBLE);

                //切换需要展示的数据源
                mBinding.list.setAdapter(receiveAdapter);
                if (receiveAdapter.getDatas().size() > 0) {
                    mBinding.list.setVisibility(View.VISIBLE);
                    mBinding.emptyOfferLay.setVisibility(View.GONE);
                } else {
                    mBinding.list.setVisibility(View.GONE);
                    mBinding.emptyOfferLay.setVisibility(View.VISIBLE);
                }

                if (sheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
                    sheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                }
                break;

            case R.id.shipped_tab_ll://点击已发货
                currTab = 2;
                mBinding.offerTabTv.setTextColor(Color.parseColor("#333333"));
                mBinding.offerTabTv.setBold(WSTextView.BOLD_REGULAR);
                mBinding.offerTabStrip.setVisibility(View.INVISIBLE);
                mBinding.receiveTabTv.setTextColor(Color.parseColor("#333333"));
                mBinding.receiveTabTv.setBold(WSTextView.BOLD_REGULAR);
                mBinding.receiveTabStrip.setVisibility(View.INVISIBLE);
                mBinding.shippedTabTv.setTextColor(Color.parseColor("#EF4033"));
                mBinding.shippedTabTv.setBold(WSTextView.BOLD_MEDIUM);
                mBinding.shippedTabStrip.setVisibility(View.VISIBLE);

                //切换需要展示的数据源
                mBinding.list.setVisibility(View.GONE);
                mBinding.emptyOfferLay.setVisibility(View.VISIBLE);

                if (sheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
                    sheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                }
                break;

            case R.id.arrive_time_ll://到场时间选择
                if (arriveTimePop.isShowing()) {
                    arriveTimePop.dismiss();
                } else {
                    arriveTimePop.showAsDropDown(mBinding.filterBarBelowView, 0, 0);
                    setFilterTabStatues(mBinding.arriveTimeLl, mBinding.arriveTimeTv, mBinding.arriveTimeIv, 2);
                }
                break;

            case R.id.car_type_ll://车型选择
                if (carTypePop.isShowing()) {
                    carTypePop.dismiss();
                } else {
                    carTypePop.showAsDropDown(mBinding.filterBarBelowView, 0, 0);
                    setFilterTabStatues(mBinding.carTypeLl, mBinding.carTypeTv, mBinding.carTypeIv, 2);
                }
                break;

            case R.id.distance_iv_ll://距装货地选择
                if (distancePop.isShowing()) {
                    distancePop.dismiss();
                } else {
                    distancePop.showAsDropDown(mBinding.filterBarBelowView, 0, 0);
                    setFilterTabStatues(mBinding.distanceIvLl, mBinding.distanceTv, mBinding.distanceIv, 2);
                }
                break;

            case R.id.filter_more://更多筛选
                morePop.showAsDropDown(mBinding.filterBarBelowView, 0, 0);
                mBinding.bgFilterPop.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
     * 列表页上拉加载更多数据信息
     */
    private void loadingMoreData() {
        if (currTab == 0) {
            viewModel.searchEntity.setSearchType(0);
            viewModel.getTickSizeListInfo(this, true);
        } else if (currTab == 1) {
            viewModel.searchEntity.setSearchType(2);
            viewModel.getTickSizeListInfo(this, true);
        }
    }

    /**
     * 筛选条件tab状态
     *
     * @param ll
     * @param tv
     * @param iv
     * @param type 0——收起，1——收起选中，2——展开
     */
    private void setFilterTabStatues(LinearLayout ll, TextView tv, ImageView iv, int type) {
        switch (type) {
            case 0:
                mBinding.bgFilterPop.setVisibility(View.GONE);
                ll.setBackgroundResource(R.drawable.app_bg_filter_gray_15dp);
                iv.setImageResource(R.mipmap.ic_down_arrow_n);
                tv.setSelected(false);
                break;

            case 1:
                mBinding.bgFilterPop.setVisibility(View.GONE);
                ll.setBackgroundResource(R.drawable.shape_theme_coner);
                iv.setImageResource(R.mipmap.ic_down_arrow);
                tv.setSelected(true);
                break;

            case 2:
                mBinding.bgFilterPop.setVisibility(View.VISIBLE);
                ll.setBackgroundResource(R.drawable.app_bg_filter_gray_15dp);
                iv.setImageResource(R.mipmap.ic_up_arrow_n);
                tv.setSelected(false);
                break;
        }
    }

    /**
     * 显示货源相关信息
     *
     * @param sourceDetail
     */
    public void setDetail(OwnerGoodsDetailInfo sourceDetail) {
        if (sourceDetail == null)
            return;
        //每次更新货源信息，需要重置高度，重新计算
        detailInfo = sourceDetail;
        refreshStatistics();
        peekHeight = 165;
        routeAddressCompleted = false;
        goodsDetailsCompleted = false;
        mBinding.include.titleView.setText(sourceDetail.getCityName() + " " + sourceDetail.getDistrictName()
                + " -> " + sourceDetail.getDestCityName() + " " + sourceDetail.getDestDistrictName() + "货运项目");
        mBinding.include.titleView.setVisibility(View.VISIBLE);
        viewModel.addAllMarkers(this, 0);

        //获取货源报价和接单的相关信息
        viewModel.searchEntity.setSearchType(-1);
        viewModel.searchEntity.setGoodsSourceNo(sourceDetail.getNo());
        viewModel.getTickSizeListInfo(this, false);

        /////////////////////设置货源相关信息
        //发货起始地
        String addStr = "";
        if (!TextUtils.isEmpty(sourceDetail.getCityName())) {
            addStr += sourceDetail.getCityName() + " ";
        }
        if (!TextUtils.isEmpty(sourceDetail.getDistrictName())) {
            addStr += sourceDetail.getDistrictName() + " → ";
        } else {
            if (!TextUtils.isEmpty(sourceDetail.getCityName()))
                addStr += " → ";
        }
        if (!TextUtils.isEmpty(sourceDetail.getDestCityName())) {
            addStr += sourceDetail.getDestCityName() + " ";
        }
        if (!TextUtils.isEmpty(sourceDetail.getDestDistrictName())) {
            addStr += sourceDetail.getDestDistrictName();
        }
        mBinding.routeAddress.setText(addStr);

        //根据地址信息高度动态改变 BottomSheetBehavior 的 PeekHeight(探出高度)
        mBinding.routeAddress.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int lineCount = mBinding.routeAddress.getLineCount();
                if (lineCount > 1) {
                    peekHeight += 20;
                }
                mBinding.routeAddress.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                routeAddressCompleted = true;
                setPeekHeight(peekHeight);
            }
        });

        //根据货物信息高度动态改变 BottomSheetBehavior 的 PeekHeight(探出高度)
        mBinding.goodsDetails.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int lineCount = mBinding.goodsDetails.getLineCount();
                if (lineCount > 1) {
                    peekHeight += 16;
                }
                mBinding.goodsDetails.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                goodsDetailsCompleted = true;
                setPeekHeight(peekHeight);
            }
        });

        //运程
        if (sourceDetail.getPlace() != null && !TextUtils.isEmpty(sourceDetail.getPlace().getTotalDistance())) {
            if (Double.valueOf(sourceDetail.getPlace().getTotalDistance()) < 1000) {
                mBinding.haul.setText("运程：1km以内");
            } else {
                mBinding.haul.setText(String.format("运程：约%skm", StringUtil.fromatUpDistance(sourceDetail.getPlace().getTotalDistance()) + ""));
            }
        }

        //货物信息
        String goodsInfo = "";
        if (!TextUtils.isEmpty(sourceDetail.getGoodsTypesName())) {
            goodsInfo += sourceDetail.getGoodsTypesName() + " ";
        }
        if (!TextUtils.isEmpty(sourceDetail.getWeight())) {
            goodsInfo += NumberUtil.trim0(sourceDetail.getWeight()) + "吨 ";
        }
        if (!TextUtils.isEmpty(sourceDetail.getVolume())) {
            goodsInfo += NumberUtil.trim0(sourceDetail.getVolume()) + "方";
        }
        if (!TextUtils.isEmpty(goodsInfo)) {
            mBinding.goodsDetails.setText(goodsInfo);
        }

        //价格信息
        if (!TextUtils.isEmpty(sourceDetail.getFreight()) && !TextUtils.isEmpty(sourceDetail.getFreightUnit())) {
            mBinding.freightUnit.setText(NumberUtil.trim0(sourceDetail.getFreight()) + sourceDetail.getFreightUnit());
        } else {
            mBinding.freightUnit.setText("/");
        }
        if (!TextUtils.isEmpty(sourceDetail.getAllFreight())) {
            mBinding.freight.setText(NumberUtil.trim0(sourceDetail.getAllFreight()) + "元");
        } else {
            mBinding.freight.setText("/");
        }

        mBinding.mapLay.setVisibility(View.VISIBLE);
    }

    /**
     * 根据数据条数刷新列表信息
     *
     * @param total
     */
    private void refreshListInfo(int total) {
        if (total > 0) {
            mBinding.list.setVisibility(View.VISIBLE);
            mBinding.emptyOfferLay.setVisibility(View.GONE);
            setHeight(525);
        } else {
            mBinding.list.setVisibility(View.GONE);
            mBinding.emptyOfferLay.setVisibility(View.VISIBLE);
            setHeight(380);
        }
    }

    /**
     * 初始化地图（高德3D地图）
     */
    private void initMap() {
        if (aMap == null)
            aMap = mapView.getMap();
        viewModel.setAMap(aMap);
        /**
         * 设置一些amap的属性
         */
        aMap.getUiSettings().setZoomControlsEnabled(true);//是否可以缩放
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));//缩放比例
        //地图文字的Z轴指数,设置为2可以将地图底图文字设置在添加的覆盖物之上
        aMap.setMapTextZIndex(2);
        UiSettings uiSettings = aMap.getUiSettings();//地图的UI设置控制器
        uiSettings.setCompassEnabled(false);// 设置指南针是否显示
        uiSettings.setZoomControlsEnabled(false);// 设置缩放按钮是否显示
        uiSettings.setScaleControlsEnabled(true);// 设置比例尺是否显示
        uiSettings.setRotateGesturesEnabled(true);// 设置地图旋转是否可用
        uiSettings.setTiltGesturesEnabled(true);// 设置地图倾斜是否可用
        uiSettings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，
        //保存地图当前的状态
        mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    private void setHeight(int dp) {
        ViewGroup.LayoutParams params = mBinding.layoutBehavior.getLayoutParams();
        params.height = ResolutionUtil.dp2px(this, dp);
        mBinding.layoutBehavior.setLayoutParams(params);
    }

    /**
     * 货主同意了某条报价信息，需要刷新页面状态
     */
    public void agreeOfferRefresh(boolean sendEvent) {
        if (sendEvent)
            EventBus.getDefault().post(LogisticsEvent.make(EventConstant.EVENT_GOODS_AGREED_OFFER, null));

        //统一报价或者接单后刷新数据（报价状态会变化）
        viewModel.getTickSizeListInfo(this, false);
    }


    @Override
    public void onResult(int position) {
        Intent intent = new Intent();
        switch (position) {
            case 0://发布货源
                //未登录前往登录页面
                if (!UserOperating.getInstance().isLogged()) {
                    VerificationCodeLoginActivity.start(this);
                } else {
                    boolean personAuth = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
                    int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
                    pushGoodsInfo(personAuth, type);
                }
                break;

            case 1://首页
                intent.putExtra("showPage", "FRAGMENT_MAIN");
                MainActivity.start(this, intent);
                finish();
                break;

            case 2://消息
                intent.putExtra("showPage", "FRAGMENT_CHAT");
                MainActivity.start(this, intent);
                finish();
                break;

            case 3://我的
                intent.putExtra("showPage", "FRAGMENT_ME");
                MainActivity.start(this, intent);
                finish();
                break;
        }
    }

    /**
     * 验证用户信息并发布货源
     *
     * @param personAuth
     * @param type       0个人 1企业 2团队
     */
    private void pushGoodsInfo(boolean personAuth, int type) {
        if (personAuth) {
            if (UserOperating.getInstance().getUserInfo() == null) {
                return;
            }
            if (type == 0) {//个人
//                if (!UserOperating.getInstance().getUserInfo().isDriverOpenFundsAccount()) {
//                    new RoundDialog.Builder(this)
//                            .title("提示")
//                            .content("开通在线收款账户后\n可使用此功能")
//                            .cancel("知道了")
//                            .confirm("前往开户")
//                            .contentGravity(Gravity.CENTER)
//                            .cancelable(false)
//                            .confirmCallback(v -> {
//                                OpenAccountFirstActivity.start(this, true);
//                            })
//                            .show();
//                    return;
//                }
                PublishCargoActivity.start(this, false);
            } else if (type == 2) {//当前团队
//                    if (!UserOperating.getInstance().getUserInfo().isDriverOpenFundsAccount()) {
//                        new RoundDialog.Builder(this)
//                                .title("提示")
//                                .content("开通在线收款账户后\n可使用此功能")
//                                .cancel("知道了")
//                                .confirm("前往开户")
//                                .contentGravity(Gravity.CENTER)
//                                .cancelable(false)
//                                .confirmCallback(v -> {
//                                    OpenAccountFirstActivity.start(this, true);
//                                })
//                                .show();
//                        return;
//                    }
                PublishCargoActivity.start(this, false);
            } else {//当前企业
                if (!UserOperating.getInstance().getUserInfo().isOpenFundsAccount()) {
//                    new RoundDialog.Builder(this)
//                            .title("提示")
//                            .content("开通在线收款账户后\n可使用此功能")
//                            .cancel("知道了")
//                            .confirm("前往开户")
//                            .contentGravity(Gravity.CENTER)
//                            .cancelable(false)
//                            .confirmCallback(v -> {
//                                OpenAccountFirstActivity.start(this, false);
//                            })
//                            .show();
//                    return;
                }
                if (UserOperating.getInstance().hasCompanyPermission(PermissionCheckUtil.KEY_HUOYUANGUANLI)) {//个人加入企业有权限
                    PublishCargoActivity.start(this, false);
                } else {
                    new RoundDialog.Builder(this)
                            .title("提示")
                            .content(UserOperating.getInstance().getTeamOrCompanyName() + "未授予您发布货源的权限。建议您联系管理员分配权限")
                            .singleBtn(true)
                            .confirm("我知道了")
                            .contentGravity(Gravity.CENTER)
                            .cancelable(false)
                            .show();
                }
            }
        } else {//去实名认证
            new RoundDialog.Builder(this)
                    .title("提示")
                    .content("您当前未实名认证，是否立即认证？")
                    .cancel("取消")
                    .confirm("确定")
                    .contentGravity(Gravity.CENTER)
                    .cancelable(false)
                    .confirmCallback(v -> {
                        AuthActivity3.start(QuotedOwnerActivity.this);
                    })
                    .show();
        }
    }

    @Override
    public void onResult(FreightProEntity entity) {
        if (entity != null && !TextUtils.isEmpty(entity.getNo())) {
            if (goodsNo != null && goodsNo.equals(entity.getNo())) {
                //如果竞价货运项目没有做任何切换，不做任何处理

            } else {
                goodsNo = entity.getNo();
                resetFilter();
                viewModel.getOwnerGoodsDetailInfo(this, goodsNo);
            }
        }
    }

    /**
     * 切换货运项目，重置筛选条件
     */
    private void resetFilter() {
        viewModel.searchEntity.setSearchType(-1);
        viewModel.searchEntity.setStartInTime("");
        viewModel.searchEntity.setEndInTime("");
        viewModel.searchEntity.setCarTypeNo("");
        viewModel.searchEntity.setOfferType("");
        viewModel.searchEntity.setDistancePlace(null);

        setFilterTabStatues(mBinding.arriveTimeLl, mBinding.arriveTimeTv, mBinding.arriveTimeIv, 0);
        setFilterTabStatues(mBinding.distanceIvLl, mBinding.distanceTv, mBinding.distanceIv, 0);
        mBinding.distanceTv.setText("距装货地");
        setFilterTabStatues(mBinding.carTypeLl, mBinding.carTypeTv, mBinding.carTypeIv, 0);
        mBinding.carTypeTv.setText("车型");

        arriveTimePop.resetData();
        distancePop.resetSelectItem();
        carTypePop.resetSelectItem();
        morePop.resetSelectItem();
    }

    /**
     * 设置 BottomSheetBehavior 的 PeekHeight(探出高度)
     */
    private void setPeekHeight(int height) {
        if (sheetBehavior != null && goodsDetailsCompleted && routeAddressCompleted) {
            sheetBehavior.setPeekHeight(DisplayUtil.convertDpToPixel(getApplicationContext(), height));
        }
    }
}
